<template>
  <!-- 特征池 -->
  <basic-container>
    <avue-crud :defaults.sync="defaults" :option="option" :table-loading="loading" :data="data" :page.sync="page"
      :permission="permissionList" :before-open="beforeOpen" v-model="form" ref="crud" @row-update="rowUpdate"
      @row-save="rowSave" @row-del="rowDel" @search-change="searchChange" @search-reset="searchReset"
      @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
      @refresh-change="refreshChange" @on-load="onLoad">
      <!-- <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAdd">添加
        </el-button>
      </template> -->
      <!-- <template slot-scope="{type,disabled}" slot="listForm">
        <el-row v-if="['add', 'edit'].includes(type)">
         
          <el-col :span="3">
            <el-button class="el-icon-plus" type="primary" round @click="test()"></el-button>
          </el-col>
        </el-row>
      </template> -->
      <template slot-scope="scope" slot="menuLeft">
        <el-button type="primary" icon="el-icon-plus" size="small" @click.stop="handleAdd">新增特征</el-button>
      </template>
    </avue-crud>
    <el-dialog :title="text" :visible.sync="dialogFormVisible" :width="dialogWidth" @opened="opened" @close="close"
      :close-on-click-modal="false" append-to-body="true" modal-append-to-body="false">
      <featurePoolAdd></featurePoolAdd>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="submitForm()">确 定</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove } from "@/api/system/featurePool";
import { mapGetters } from "vuex";
import website from "@/config/website";
import featurePoolAdd from '@/views/system/featurePoolAdd/index.vue'
export default {
  data() {
    return {
      dialogWidth: '70%',
      dialogFormVisible: false,
      text: '',
      submitType: '',
      dynamicIndex: 0,
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      defaults: {},
      option: {
        dialogFullscreen: true,
        labelWidth: 120,
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 5,
        border: true,
        index: true,
        viewBtn: true,
        addBtn: false,
        refreshBtn: false,
        columnBtn: false,
        searchShowBtn: false,
        dialogClickModal: false,
        column: [
          {
            label: "特征名称",
            prop: "characteristicName",
            search: true,
            rules: [{
              required: true,
              message: "请输入特征名称",
              trigger: "blur"
            }]
          },
          {
            label: "特征编号",
            prop: "characteristicCode",
            search: true,
            rules: [{
              required: true,
              message: "请输入特征编号",
              trigger: "blur"
            }]
          },
          {
            label: "特征单位",
            prop: "unit",

            rules: [{
              required: true,
              message: "请输入特征单位",
              trigger: "blur"
            }]
          },
          {
            label: '特征池描述',
            prop: 'descriptions',
            // type: 'textarea',
            minRows: 2,
            maxRows: 5,
            hide: true,
            // span: 24
          },
          {
            label: '是否配置指标',
            prop: 'isTarget',
            type: 'radio',
            hide: true,
            span: 24,
            dicData: [{
              label: '是',
              value: true
            }, {
              label: '否',
              value: false
            }],
            value: false,
            rules: [{
              required: true,
              message: "请选择",
              trigger: "change"
            }],
            // control: (val, form) => {
            //   if(val==true){
            //     return{
            //       dynamicList:{
            //         display:true
            //       }
            //     }
            //   }else{
            //     return{
            //       dynamicList:{
            //         display:false
            //       }
            //     }
            //   }
            // }
          },
          {
            label: '添加指标',
            prop: 'dynamicList',
            type: 'dynamic',
            span: 24,
            display: false,
            hide: true,
            children: {
              index: false,
              type: 'form',
              align: 'center',
              headerAlign: 'center',
              rowAdd: (done) => {
                // this.$message.success('新增回调')
                done({
                  input: '默认值',
                })
              },
              rowDel: (row, done) => {
                // this.$message.success('删除回调' + JSON.stringify(row))
                done()
              },
              column: [

                {
                  label: "指标名称",
                  prop: "targetName",
                  span: 8,
                  rules: [{
                    required: true,
                    message: "请输入特征名称",
                    trigger: "blur"
                  }]
                },
                {
                  label: "指标编号",
                  prop: "targetCode",
                  span: 8,
                  rules: [{
                    required: true,
                    message: "请输入特征编号",
                    trigger: "blur"
                  }]
                },
                {
                  label: "数据类型",
                  prop: "dataKey",
                  type: "select",
                  span: 8,
                  hide: true,
                  dicUrl: '/api/blade-platform/characteristicPool/dataType',
                  rules: [{
                    required: true,
                    message: "请选择特征类型",
                    trigger: "change"
                  }],
                  //TODO:官方有bug，先采取监听方式处理
                  // control: (val, form) => {
                  //   this.dynamicIndex=form.$index 
                  //   // const self=this
                  //   console.log('数据类型', val, form);
                  //   debugger
                  //   if (val == 'STRING' || val == 'BOOLEAN') {
                  //     return{
                  //       floatValue:{
                  //         display:true
                  //       }
                  //     }
                  //   }else{
                  //     return{
                  //       floatValue:{
                  //         display:false
                  //       }
                  //     }
                  //   }
                  // }
                },
                {
                  label: '照片',
                  prop: 'imgUrl3',
                  type: 'upload',
                  drag: true,
                  hide: true,
                  display: false,
                  listType: 'picture-img',
                  loadText: '图片上传中，请稍等',
                  span: 24,
                  tip: '只能上传jpg/png格式的图片',
                  propsHttp: {
                    res: 'data',
                    url: 'link',
                  },
                  action: "/api/blade-resource/oss/endpoint/put-file?code=minio"
                },
                {
                  label: '枚举项',
                  prop: 'enumKey',
                  type: 'url',
                  // alone: true,
                  display: false,
                  hide: true,
                  viewDisplay: false,
                  value: []
                },
                {
                  // label: '单个超链接框',
                  prop: 'enumValue',
                  display: false,
                  hide: true,
                  viewDisplay: false,
                  // alone: true,
                  type: 'url',
                  value: []
                },
                {
                  label: '布尔值',
                  prop: 'boolKey',
                  // alone: true,
                  display: false,
                  viewDisplay: false,
                  hide: true,
                  type: 'url',
                  limit: 2,
                  value: []
                },
                {
                  // label: '单个超链接框',
                  prop: 'boolValue',
                  // alone: true,
                  display: false,
                  hide: true,
                  type: 'url',
                  limit: 2,
                  viewDisplay: false,
                  value: []
                },
                {
                  label: "最小值",
                  prop: "floatKey",
                  type: 'number',
                  display: false,
                  span: 8,
                  hide: true,
                  rules: [{
                    required: true,
                    message: "请输入",
                    trigger: "blur"
                  }]
                },
                {
                  label: "最大值",
                  prop: "floatValue",
                  type: 'number',
                  display: false,
                  span: 8,
                  hide: true,
                  rules: [{
                    required: true,
                    message: "请输入",
                    trigger: "blur"
                  }]
                },
              ]
            },
          },
          {
            label: "数据类型",
            prop: "dataKey",
            display: false,
            type: "select",
            span: 24,
            hide: true,
            dicUrl: '/api/blade-platform/characteristicPool/dataType',
            rules: [{
              required: true,
              message: "请选择特征类型",
              trigger: "change"
            }]
          },
          {
            label: '照片',
            prop: 'imgUrl3',
            type: 'upload',
            drag: true,
            hide: true,
            display: false,
            listType: 'picture-img',
            loadText: '图片上传中，请稍等',
            span: 24,
            tip: '只能上传jpg/png格式的图片',
            propsHttp: {
              res: 'data',
              url: 'link',
            },
            action: "/api/blade-resource/oss/endpoint/put-file?code=minio"
          },
          {
            label: '枚举项',
            prop: 'enumKey',
            type: 'url',
            // alone: true,
            display: false,
            hide: true,
            viewDisplay: false,
            value: []
          },
          {
            // label: '单个超链接框',
            prop: 'enumValue',
            display: false,
            hide: true,
            viewDisplay: false,
            // alone: true,
            type: 'url',
            value: []
          },
          {
            label: '布尔值',
            prop: 'boolKey',
            // alone: true,
            display: false,
            viewDisplay: false,
            hide: true,
            type: 'url',
            limit: 2,
            value: []
          },
          {
            // label: '单个超链接框',
            prop: 'boolValue',
            // alone: true,
            display: false,
            hide: true,
            type: 'url',
            limit: 2,
            viewDisplay: false,
            value: []
          },
          {
            label: "最小值",
            prop: "floatKey",
            type: 'number',
            display: false,
            span: 8,
            hide: true,
            rules: [{
              required: true,
              message: "请输入",
              trigger: "blur"
            }]
          },
          {
            label: "最大值",
            prop: "floatValue",
            type: 'number',
            display: false,
            span: 8,
            hide: true,
            rules: [{
              required: true,
              message: "请输入",
              trigger: "blur"
            }]
          },
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        // addBtn: this.vaildData(this.permission.post_add, false),
        // viewBtn: this.vaildData(this.permission.post_view, false),
        // delBtn: this.vaildData(this.permission.post_delete, false),
        // editBtn: this.vaildData(this.permission.post_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  components: {
    featurePoolAdd,

  },
  watch: {
    // 'form.list': {
    //   handler(val) {
    //     console.log('1111', val);
    //   },
    //   immediate: true
    // },
    'form.isTarget': {
      handler(val) {
        if (val == true) {
          this.defaults.dataKey.display = false
          this.defaults.dynamicList.display = true
          // this.defaults.enumList.display = false

          this.defaults.boolKey.display = false
          this.defaults.boolValue.display = false
          this.defaults.imgUrl3.display = false
          this.defaults.floatKey.display = false
          this.defaults.floatValue.display = false
        } else if (val == false) {
          this.defaults.dataKey.display = true
          this.defaults.dynamicList.display = false
          // this.defaults.enumList.display = false
          this.defaults.boolKey.display = false
          this.defaults.boolValue.display = false
          this.defaults.imgUrl3.display = false
          this.defaults.floatKey.display = false
          this.defaults.floatValue.display = false
        }
      },
      immediate: true
    },
    // 'form.dataKey': {
    //   handler(val) {
    //     if (val == 'STRING' || val == 'BOOLEAN') {
    //       this.defaults.boolKey.display = true
    //       this.defaults.boolValue.display = true
    //       // this.defaults.dynamicList.display = false
    //       this.defaults.enumKey.display = false
    //       this.defaults.enumValue.display = false
    //       // this.defaults.enumList.display = false
    //       this.defaults.imgUrl3.display = false
    //       this.defaults.floatKey.display = false
    //       this.defaults.floatValue.display = false
    //     } else if (val == 'ENUMERATE') {
    //       this.defaults.boolKey.display = false
    //       this.defaults.boolValue.display = false
    //       // this.defaults.dynamicList.display = false
    //       this.defaults.enumKey.display = true
    //       this.defaults.enumValue.display = true
    //       // this.defaults.enumList.display = true
    //       this.defaults.imgUrl3.display = false
    //       this.defaults.floatKey.display = false
    //       this.defaults.floatValue.display = false
    //     } else if (val == 'FLOAT') {
    //       this.defaults.boolKey.display = false
    //       this.defaults.boolValue.display = false
    //       // this.defaults.dynamicList.display = false
    //       this.defaults.enumKey.display = false
    //       this.defaults.enumValue.display = false
    //       // this.defaults.enumList.display = false
    //       this.defaults.imgUrl3.display = false
    //       this.defaults.floatKey.display = true
    //       this.defaults.floatValue.display = true
    //     } else if (val == 'PICTURE') {
    //       this.defaults.boolKey.display = false
    //       this.defaults.boolValue.display = false
    //       // this.defaults.dynamicList.display = false
    //       this.defaults.enumKey.display = false
    //       this.defaults.enumValue.display = false
    //       // this.defaults.enumList.display = false
    //       this.defaults.imgUrl3.display = true
    //       this.defaults.floatKey.display = false
    //       this.defaults.floatValue.display = false
    //     } else {
    //       this.defaults.boolKey.display = false
    //       this.defaults.boolValue.display = false
    //       // this.defaults.dynamicList.display = false
    //       this.defaults.enumKey.display = false
    //       this.defaults.enumValue.display = false
    //       // this.defaults.enumList.display = false
    //       this.defaults.imgUrl3.display = false
    //       this.defaults.floatKey.display = false
    //       this.defaults.floatValue.display = false
    //     }
    //   },
    //   immediate: true
    // },
    // 'form.dynamic': {
    //   handler(val) {
    //     if(val&&val[0]){
    //       if (val[0].dataKey1 =='STRING') {
    //       //如果是多个指标，这里的逻辑是不对的，一个改变会影响所有组
    //       this.defaults.dynamic.children.column[8].display = true
    //       this.defaults.dynamic.children.column[9].display = true
    //     } else {
    //       this.defaults.dynamic.children.column[8].display = true
    //       this.defaults.dynamic.children.column[9].display = true
    //     }
    //     }
    //     // val.forEach((element) => {
    //     //   debugger
    //     //   const dataKey1=element.dataKey1
    //     //   if (dataKey1 == 'STRING' || dataKey1 == 'BOOLEAN') {
    //     //     self.defaults.dynamic.children.column[9].display = false
    //     //     // self.defaults.dynamic.children.column[9].display = true
    //     //     // self.defaults.dynamic.children.column[9].display = false
    //     //   }
    //     // });
    //     // const index = this.getValIndex(val)
    //     // if (val[0].select == 1) {
    //     //   //如果是多个指标，这里的逻辑是不对的，一个改变会影响所有组
    //     //   this.defaults.dynamic.children.column[3].display = true
    //     //   this.defaults.dynamic.children.column[4].display = false
    //     // } else if (index.select == 2) {
    //     //   this.defaults.dynamic.children.column[3].display = false
    //     //   this.defaults.dynamic.children.column[4].display = true
    //     // }
    //   },
    //   deep: true,
    // },
    'form.dynamicList': {
      handler(val) {
        debugger
        const self = this
        if (val) {
          val.forEach((element, index) => {
            if (index == self.dynamicIndex) {
              const key = element.dataKey
              if (key == 'STRING' || key == 'BOOLEAN') {
                console.log('this.dynamicIndex', this.dynamicIndex);
                self.defaults.dynamicList.children.column[6].display = true//布尔key
                self.defaults.dynamicList.children.column[7].display = true//布尔value
              } else if (key == 'ENUMERATE') {
                self.defaults.dynamicList.children.column[4].display = true//枚举key
                self.defaults.dynamicList.children.column[5].display = true//举value
              } else if (key == 'FLOAT') {
                self.defaults.dynamicList.children.column[8].display = true//最小值
                self.defaults.dynamicList.children.column[9].display = true//最大值
              } else if (key == 'PICTURE') {
                self.defaults.dynamicList.children.column[3].display = true//图片
              } else {

              }
            }

          });
        }

      },
      immediate: true
    }

  },
  methods: {
    handleAdd() {
      this.submitType = 'add'
      this.dialogFormVisible = true
      this.text = '新增特征池规则'
    },
    handleAdd1(row) {
      // const statusNew = statusList.find((x) => {
      //   if (x.value == row.offLineStatus) {
      //     return true
      //   }
      // })

      this.$router.push({
        path: '/characteristicManageDetail',
        // query: {
        //   equipmentId: row.equipmentId,
        //   productId: row.productId,
        //   offLineStatus: statusNew.label,
        //   insertTime: row.insertTime,
        // },
      })
    },
    rowSave(row, done, loading) {
      console.log('特征池添加', JSON.stringify(row))
      let item = {}
      if (row.isTarget) {
        //配置指标
        const { characteristicCode, characteristicName, descriptions, isTarget, unit, boolKey, boolValue, enumKey, enumValue } = row
        item = {
          characteristicCode,
          characteristicName,
          descriptions,
          isTarget,
          unit
        }
        console.log('特征池添加-配置指标数据处理', JSON.stringify(item))
      } else {
        const {
          characteristicCode,
          characteristicName,
          dataKey,
          descriptions,
          isTarget,
          unit,
          boolKey,
          boolValue,
          enumKey,
          enumValue,
          floatKey,
          floatValue,
          imgUrl3
        } = row
        const arry = []
        if (dataKey == ('STRING' || 'BOOLEAN')) {
          boolValue.forEach((element, index) => {
            arry.push({
              characteristicKey: boolKey[index],
              characteristicPictureUrl: '',
              characteristicValue: element
            })
          });
        } else if (dataKey == 'ENUMERATE') {
          enumValue.forEach((element, index) => {
            arry.push({
              characteristicKey: enumKey[index],
              characteristicPictureUrl: '',
              characteristicValue: element
            })
          });
        } else if (dataKey == 'FLOAT') {
          arry.push({
            characteristicKey: floatKey,
            characteristicPictureUrl: '',
            characteristicValue: floatValue
          })
        } else if (dataKey == 'PICTURE') {
          const url = imgUrl3 && imgUrl3[0] && imgUrl3[0].label
          arry.push({
            characteristicKey: '',
            characteristicPictureUrl: url,
            characteristicValue: ''
          })
        }
        item = {
          characteristicCode,
          characteristicName,
          descriptions,
          isTarget,
          unit,
          dataKey,
          dataTableDTOS: arry
        }
        console.log('特征池添加-未配置指标数据处理', JSON.stringify(item))
      }
      add(item).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      console.log('特征池添加', JSON.stringify(row))
      const { id, characteristicCode, characteristicName, dataKey, descriptions, isTarget, unit, list } = row
      let item = {
        id, characteristicCode, characteristicName, dataKey, descriptions, isTarget, unit,
      }
      const targetList = []
      if (this.form.isTarget == 1) {
        list.forEach((element) => {
          targetList.push({
            dataKey: element.dataKey,
            targetCode: element.targetCode,
            targetName: element.targetName
          })
        });
        item = {
          ...item,
          list: targetList
        }
      }
      console.log('特征池编辑-处理数据', JSON.stringify(item))
      update(item).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          const data = res.data.data
          this.form = data
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style></style>
